/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2020-05-06 15:21
 */
package com.yao.common.util;

import com.yao.common.helper.SpringFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * redis 工具类
 * 
 * @author yaoyuming
 * @date 2020/05/06 15:21
 */
public class RedisUtils {

    /**
     * 默认过期时长，单位：秒
     */
    private static final long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**
     * 不设置过期时长
     */
    private static final long NOT_EXPIRE = -1;
    private static RedisTemplate<String, String> redisTemplate;

    public static RedisTemplate<String, String> getRedisTemplate() {
        if (null == redisTemplate) {
            redisTemplate = SpringFactory.getBean(StringRedisTemplate.class);
        }
        return redisTemplate;
    }

    public static void del(String key) {
        getRedisTemplate().delete(key);
    }

    public static void del(String... keys) {
        Set<String> kSet = Stream.of(keys).collect(Collectors.toSet());
        getRedisTemplate().delete(kSet);
    }

    public static void del(Collection<String> keys) {
        Set<String> kSet = keys.stream().collect(Collectors.toSet());
        getRedisTemplate().delete(kSet);
    }

    public static void set(String key, String value) {
        getRedisTemplate().opsForValue().set(key, value);
    }

    public static void set(String key, String value, long expTime) {
        if(0L == expTime){
            expTime = DEFAULT_EXPIRE;
        }
        getRedisTemplate().opsForValue().set(key, value, expTime, TimeUnit.MINUTES);
    }

    public static String get(String key) {
        return getRedisTemplate().opsForValue().get(key);
    }

}